package no.zsoft.multitenant.hibernate;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.dbcp.datasources.PerUserPoolDataSource;
import org.apache.commons.dbcp.datasources.PerUserPoolDataSourceFactory;
import org.hibernate.service.jdbc.connections.spi.AbstractDataSourceBasedMultiTenantConnectionProviderImpl;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

public class MultiTenantConnectionProviderImpl extends
		AbstractDataSourceBasedMultiTenantConnectionProviderImpl {

	Map<String, DataSource> map;
	
	public MultiTenantConnectionProviderImpl() {
		
		init();			
		
	}

	private void init() {
		
		DataSource appDs=new DriverManagerDataSource("com.mysql.jdbc.Driver","jdbc:mysql://localhost/multitenant_app?createDatabaseIfNotExist=true&amp;useUnicode=true&amp;characterEncoding=utf-8","root","1");
		
		JdbcTemplate jdbcTemplate= new JdbcTemplate(appDs);
		List<String> tenantList = jdbcTemplate.queryForList("select tenant from t_user",String.class);
			

		map = new HashMap<String, DataSource>();
		for (String tenant : tenantList) {
			DataSource dataSource1=new DriverManagerDataSource("com.mysql.jdbc.Driver","jdbc:mysql://localhost/"+tenant+"?createDatabaseIfNotExist=true&amp;useUnicode=true&amp;characterEncoding=utf-8","root","1");
			map.put(tenant, dataSource1);
		}
	}

	@Override
	protected DataSource selectAnyDataSource() {

		DataSource dataSource = map.get("mehdi");
		if(dataSource==null) {
			init();
			dataSource = map.get("mehdi");
		}
		
		return dataSource;
	}

	@Override
	protected DataSource selectDataSource(String tenantIdentifier) {
		System.err.println("tenantIdentifier************"+tenantIdentifier);
		
		DataSource dataSource = map.get(tenantIdentifier);
		
		if(dataSource==null) {
			System.err.println("tenantIdentifier************"+tenantIdentifier+"is ="+dataSource);
			init();
			dataSource = map.get(tenantIdentifier);
			System.err.println("tenantIdentifier************"+tenantIdentifier+"is after ="+dataSource);
		}
		return dataSource;
	}

	public void setMap(Map<String, DataSource> map) {
		this.map = map;
	}

}
